<template>
	<view>
		<view v-if="canIUse" class="authorize">
			<view class='top'>
				<image src='../../static/images/loginBg.jpg' mode="scaleToFill"></image>
			</view>

			<view class='contents'>
				<view class="loginTitle">登录说明</view>
				<view class="loginTitle1">注：手机连接房间wifi才能使用哦~</view>
				<!--  #ifdef MP-WEIXIN -->
				<view class="loginTitle2">先申请登录，然后扫描房间巨幕二维码进入</view>
				<!--  #endif -->
				
				<!--  #ifdef APP-PLUS -->
				<view class="loginTitle2">先注册或者微信授权登录，然后扫描房间巨幕二维码进入</view>
				<!--  #endif -->
				<view class="info-wrap">
					<view class="info-wrap-item">
						<view class="info">
							<view class="info-item">
								<image src="../../static/images/tabBarIcon/sucai2.png" mode="scaleToFill"></image>
								<text>播放效果</text>
							</view>
						</view>
						<view class="info">
							<view class="info-item">
								<image src="../../static/images/tabBarIcon/danmu2.png"></image>
								<text>发送弹幕</text>
							</view>
						</view>
					</view>
					<view class="info-wrap-item">
						<view class="info">
							<view class="info-item">
								<image src="../../static/images/tabBarIcon/changjing2.png" mode=""></image>
								<text>播放模式</text>
							</view>
						</view>
						<view class="info">
							<view class="info-item">
								<image src="../../static/images/tabBarIcon/baping2.png" mode=""></image>
								<text>发送霸屏</text>
							</view>
						</view>
					</view>
				</view>
			</view>

			<!-- 小程序端 -->
			<!--  #ifdef MP-WEIXIN -->
			<view class='bottom'>
				<button v-if="!hasUserInfo && canIUse" open-type="getUserInfo" @getuserinfo="getUserInfo"> 申请登录 </button>
				<button @tap="toChat">{{loginMsg}}</button>
			</view>
			<!--  #endif -->

			<!-- app端 -->
			<!--  #ifdef APP-PLUS -->
			<view class='bottom' style="width: 100%;">
				<button @tap="toRegister" class="margin-right-sm" data-target="Modal" style="display: inline-block;"> 注册 </button>
				<button @click="appLogin" class="margin-right-sm" style="display: inline-block;">微信授权登录</button>
				<button @tap="control" class="margin-right-sm" style="display: inline-block;">控制器</button>
				<button @tap="toChat" class="margin-right-sm" style="display: inline-block;">{{loginMsg}}</button>
			</view>
			<!--  #endif -->
		</view>

		<!--  #ifdef MP-WEIXIN -->
		<view v-else>请升级微信版本</view>
		<!--  #endif -->

		<view class="cu-modal" :class="modalName=='Modal'?'show':''">
			<view class="cu-dialog">
				<view class="cu-bar bg-white justify-end">
					<view class="content">个人信息</view>
					<view class="action" @tap="hideModal">
						<text class="cuIcon-close text-red"></text>
					</view>
				</view>
				<view class="padding-sm">
					<!-- <view class="cu-form-group">
						<view class="title" @tap="uploadHeaderImg">头&nbsp;&nbsp;&nbsp;像</view>
						<text class="text-grey text-sm" @tap="uploadHeaderImg">请上传头像！</text>
						<avatar selWidth="200px" selHeight="400upx" @upload="myUpload" :avatarSrc="headerImg" ref="avatar" avatarStyle="width: 70upx; height: 70upx;"
						 style="margin-top: 5px;"></avatar>
					</view> -->
					<view class="cu-form-group">
						<view class="title">IP</view>
						<input v-model="serverIP" placeholder="请输入IP地址..." name="input"></input>
					</view>
					<view class="cu-form-group">
						<view class="title">用户名</view>
						<input v-model="nickName" placeholder="请输入用户名..." name="input"></input>
					</view>
				</view>
				<view class="cu-bar bg-white">
					<view class="action margin-0 flex-sub text-green">
						<view class="action margin-0 flex-sub text-green" @tap="hideModal">取消</view>
						<view class="action margin-0 flex-sub" @tap="saveUserInfo">确定</view>
					</view>
				</view>
			</view>
		</view>
		<!-- 密码校验 -->
		<check-pwd ref="pwd" :localServerIP="localIP"></check-pwd>
	</view>
</template>

<script>
	const app = getApp();
	// import websocket from '../../utils/websocket.js';
	
	import http from '../../utils/http.js'
	import utils from '../../utils/util.js';
	import avatar from "../../components/yq-avatar/yq-avatar.vue";
	import checkPwd from '../../components/checkPwd/index.vue'
	export default {
		components: {
			avatar,
			checkPwd
		},
		data() {
			return {
				serverIP:'',
				modalName: 'Madol',
				userInfo: {},
				avatarUrl: '',
				headerImg: '../../static/images/headerimg.png',
				nickName: '',
				hasUserInfo: false,
				isUserInfo: false,
				isAppUserInfo: false,
				isAvatar: false,
				loginMsg: ' ♥ 扫码进入',
				canIUse: uni.canIUse('button.open-type.getUserInfo'),
				mubuIndex: 0,
				isWeChat: false, //是否有微信
				localIP: '',
			}
		},
		onLoad: function() {

			console.log(app, '--------------app----------------')
			var connectData = utils.getStor('connectData') || '';
			// 获取用户信息后，判断缓存里的ip地址是否过期，没过期就直接进入，过期扫码再加入
			if (connectData) {
				this.setData({
					loginMsg: ' ♥ 点击进入'
				})
			}

			// 登录
			//#ifdef MP-WEIXIN
			uni.login({
				success: res => {
					// ------ 获取凭证 ------
					var code = res.code;
					if (code) {
						// console.log(res);
						console.log('获取用户登录凭证：' + code);
						app.globalData.authcode = code;
						this.getOpenId();
					} else {
						console.log('获取用户登录失败：' + res.errMsg);
					}
				}
			})

			if (app.globalData.userInfo) {
				this.setData({
					userInfo: app.globalData.userInfo,
					hasUserInfo: true
				});
			} else if (this.canIUse) {
				// 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
				// 所以此处加入 callback 以防止这种情况
				// app.userInfoReadyCallback = res => {
				// 	console.log("userInfoReadyCallback",res);
				// 	app.globalData.userInfo = res.userInfo;
				// 	app.globalData.encryptedData = res.encryptedData;
				// 	app.globalData.iv = res.iv;
				// 	app.globalData.rawData = res.rawData;
				// 	app.globalData.signature = res.signature;
				// 	this.setData({
				// 		userInfo: res.userInfo,
				// 		hasUserInfo: true
				// 	});
				// }

				//获取用户信息
				uni.getSetting({
					success: res => {
						if (res.authSetting['scope.userInfo']) {
							// 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
							uni.getUserInfo({
								success: res => {
									// console.log('-----------用户信息--------')
									// console.log("userInfoReadyCallback",res);
									// 可以将 res 发送给后台解码出 unionId
									app.globalData.userInfo = res.userInfo;
									app.globalData.encryptedData = res.encryptedData;
									app.globalData.iv = res.iv;
									app.globalData.rawData = res.rawData;
									app.globalData.signature = res.signature;
									this.setData({
										userInfo: res.userInfo,
										hasUserInfo: true
									});


								}
							})
						}
					}
				})
			} else {
				// 在没有 open-type=getUserInfo 版本的兼容处理
				uni.getUserInfo({
					success: res => {
						app.globalData.userInfo = res.userInfo;
						app.globalData.encryptedData = res.encryptedData;
						app.globalData.iv = res.iv;
						app.globalData.rawData = res.rawData;
						app.globalData.signature = res.signature;
						this.setData({
							userInfo: res.userInfo,
							hasUserInfo: true
						});
					}
				})
			}
			//#endif 

			//#ifdef APP-PLUS
			if (app.globalData.userInfo == null) {

				this.setData({
					isUserInfo: false
				});
				setTimeout(() => {
					uni.showToast({
						title: '请先注册或授权登录后，再进入...',
						icon: "none",
						duration: 2000
					});
				}, 1000)
				return;
			} else {
				let userInfo = uni.getStorageSync('userInfo')
				app.globalData.userInfo = userInfo
				this.setData({
					userInfo: userInfo,
					isUserInfo: true
				});
			}
			//#endif 

			uni.getProvider({
				service: 'oauth',
				success: (res) => {
					// console.log(res.provider);
					//支持微信、qq和微博等
					if (~res.provider.indexOf('weixin')) {
						this.isWeChat = true;
					} else {
						this.isWeChat = false;
					}
				},
			})
		},
		onHide: function() {
			console.log("index--onHide");
			// uni.closeSocket();
		},
		onUnload: function() {
			console.log("index--onUnload");
			// uni.closeSocket();
		},
		methods: {
			getOpenId() {
				uni.request({
					url: app.globalData.baseURL + '/wx/user/login',
					method: "get",
					data: {
						code: app.globalData.authcode,
						appid: utils.getMiniAppInfo()
					},
					header: {
						"Content-Type": "application/json"
					},
					success: res => {
						let ret = JSON.parse(res.data);
						console.log("获取sessionkey", ret);
						if (res.statusCode == 200) {
							app.globalData.sessionKey = ret.sessionKey;
							app.globalData.openId = ret.openid;
							app.globalData.id = ret.openid;
							console.log(app.globalData.openId);
						}

					}
				});
			},
			appLogin() { //app授权登录
	
				uni.getProvider({
					service: 'oauth',
					success: (res) => {
						console.log(res.provider);
						//支持微信、qq和微博等
						if (~res.provider.indexOf('weixin')) {
							// console.log('--------------执行了--------------')
							uni.login({
								provider: 'weixin',
								success: (loginRes) => {
									console.log('-------获取openid(unionid)-----');
									console.log(JSON.stringify(loginRes));
									// 获取用户信息
									uni.getUserInfo({
										provider: 'weixin',
										withCredentials: true,
										success: (infoRes) => {
											console.log('-------获取微信用户信息-----');
											console.log(infoRes);
											console.log(JSON.stringify(infoRes.userInfo));
											app.globalData.userInfo = infoRes.userInfo;
											app.globalData.openId = infoRes.userInfo.openId;
											console.log(infoRes.userInfo.openId)
											
											uni.setStorageSync('userInfo',infoRes.userInfo);

											this.isAppUserInfo = true;

											uni.showToast({
												title: '授权成功~',
												icon: 'none'
											})
										}
									});
								},
								fail:(errMsg)=>{
									console.log(errMsg,'errMsg');
									uni.showToast({
										title: '授权失败,请重试 或者点击 注册按钮 自行注册~',
										icon: 'none',
										duration:2000
									})
									
									this.isAppUserInfo = false;
								}
							});
						}else{
							uni.showToast({
								title: '授权失败,请重试 或者点击 注册按钮 自行注册~',
								icon: 'none',
								duration:2000
							})
							
							this.isAppUserInfo = false;
						}
					}
				});
			},
			myUpload(rsp) {

				let that = this;
				// this.avatarUrl = rsp.path; //更新头像方式一

				//#ifdef APP-PLUS
				//通过URL参数获取目录对象或文件对象
				plus.io.resolveLocalFileSystemURL(rsp.path, function(entry) {
					// 可通过entry对象操作test.html文件
					entry.file(function(file) { //获取文件数据对象
						var fileReader = new plus.io.FileReader(); // 文件系统中的读取文件对象，用于获取文件的内容
						//alert("getFile:" + JSON.stringify(file));
						fileReader.readAsDataURL(file); //以URL编码格式读取文件数据内容
						fileReader.onloadend = function(evt) { //读取文件成功完成的回调函数

							// console.log(evt.target.result, 'evt.target.result')
							let base64Arr = evt.target.result.split(',')
							console.log(base64Arr[0], 'arr1')
							console.log(base64Arr[1], 'arr1')
							let base64_Path = base64Arr[1];
							that.headerImg = evt.target.result;
							that.avatarUrl = base64_Path;
							that.isUserInfo = true;

						}
					})
				})
				//#endif
			},
			setData(obj) { //转换this.xxx = xxxx
				const keys = Object.keys(obj);
				keys.forEach((key) => {
					this[key] = obj[key];
				});
			},
			clearForm: function() {
				this.isUserInfo = false;
				app.globalData.userInfo = null;
				uni.removeStorageSync('userInfo')
				utils.removeStor('connectData');
				uni.showToast({
					title: '清除成功...'
				})
			},
			toRegister: function() {
				// uni.removeStorageSync('userInfo')
				// this.headerImg = '../../static/images/headerimg.png'
				this.modalName = 'Modal'
			},
			getUserInfo: function(e) {
				console.log(e);

				console.log(JSON.stringify(e.detail.userInfo))
				if (e.detail.userInfo == undefined) {
					return;
				}
				app.globalData.userInfo = e.detail.userInfo;
				app.globalData.encryptedData = e.detail.encryptedData;
				app.globalData.iv = e.detail.iv;
				app.globalData.rawData = e.detail.rawData;
				app.globalData.signature = e.detail.signature;
				app.globalData.loginType = 0;
				this.setData({
					userInfo: e.detail.userInfo,
					hasUserInfo: true
				});
			},
			toChat: function() {

				// console.log(app.globalData.userInfo, 'app.globalData.userInfo')

				var that = this;
				var connectData = utils.getStor('connectData') || '';
				console.log(connectData);

				//#ifdef MP-WEIXIN
				app.globalData.loginType = 0;
				if (app.globalData.userInfo == null) {
					uni.showToast({
						title: '请先登录后，再进入...',
						icon: "none",
						duration: 2000
					});
					return;
				}
				//#endif 

				//#ifdef APP-PLUS
				app.globalData.loginType = 1;
				if (app.globalData.userInfo == null) {
					uni.showToast({
						title: '请先注册或者授权登录后，再进入...',
						icon: "none",
						duration: 2000
					});
					return;
				}
				//#endif 

				if (connectData) {
					this.connectSocket();
				} else {
					uni.scanCode({
						success: (res) => {
							console.log(res);
							let arr = [];
							if(res.result.indexOf("http://mp2")==0){
								arr = res.result.split("=")[1].split(",");
							}else{
								arr = res.result.split(",");
							}
							console.log(arr, 'arr');
							if (arr.length > 1) {
								utils.setStor('connectData', arr[0]);
								uni.setStorageSync('mubuIndex', arr[1]);
								app.globalData.mubuIndex = arr[1];
							}
							this.connectSocket();
						},
						fail: (res) => {
							uni.showToast({
								title: '失败',
								icon: 'success',
								duration: 2000
							})
						},
						complete: (res) => {}
					});
				}
			},
			connectSocket: function() {
				// uni.closeSocket()
				var that = this;
				var connectData = utils.getStor('connectData');

				console.log(connectData, '-----connectData-------')
				uni.showToast({
					title: '连接中...',
					icon: "none",
					duration: 500
				});
				
				uni.switchTab({
					url: '../material/material',
				})
				/*var url = 'ws://' + connectData + ':2860';
				uni.connectSocket({
					url: url,
					header: {
						'content-type': 'application/json'
					},
					success: (res) => {
						// console.log(res,'connectSocket')
						console.log('信道连接成功~');
						uni.showToast({
							title: '连接中...',
							icon: "none",
							duration: 10000
						});
					},
					fail: function() {
						console.log('信道连接失败~');
					}
				});
				uni.onSocketOpen((res) => {
					// console.log(res,'onSocketOpen')
					console.log('连接打开');
					uni.switchTab({
						url: '../material/material',
					})
				});

				uni.onSocketMessage((res) => {
					// console.log('收到服务器内容：' + res.data);
					this.onSocketMessage(res.data);
				});
				uni.onSocketError(function(res) {
					utils.removeStor('connectData');
					that.setData({
						loginMsg: ' ♥ 扫码进入'
					});
					uni.showToast({
						title: '连接设备失败，请联系工作人员！',
						icon: "none",
						duration: 2000
					});
				});
				// 监听WebSocket关闭
				uni.onSocketClose(res => {
					console.log('监听到 WebSocket 已关闭！');
				});*/
			},
			uploadHeaderImg() {
				this.$refs.avatar.fChooseImg();
				this.isUserInfo = true;
			},
			saveUserInfo() { //保存用户信息
				if (this.nickName == '') {
					uni.showToast({
						title: '请输入用户名',
						icon: 'none'
					})

					return false;
				}

				let userInfo = {
					nickName: this.nickName,
					// avatarUrl: (this.headerImg != '../../static/images/headerimg.png') ? this.avatarUrl : ''
					// avatarUrl: (this.headerImg != '../../static/images/headerimg.png') ? this.avatarUrl : ''
				}
				utils.setStor('connectData', this.serverIP);
				uni.setStorageSync('userInfo', userInfo)
				app.globalData.userInfo = userInfo;
				app.globalData.loginType = 1;
				this.modalName = '';
				this.isUserInfo = true;

				uni.showToast({
					title: '注册成功',
					duration:2000
				})
				
				if(this.serverIP != ''){
					this.connectSocket()
				}else{
					uni.showToast({
						title:'请扫码进入~',
						icon:'none',
						duration:2000
					})
				}
			},
			control() { //控制器
				this.$refs.pwd.pwdDialog = 'Modal'
				let serverIP = uni.getStorageSync('zkLocalIP') || '';

				if (serverIP == '' || serverIP == undefined) {
					this.localIP = serverIP
				} else {
					this.localIP = serverIP
				}
			},
			hideModal() {
				this.modalName = '';
				this.isUserInfo = false;
				this.nickName = '';
				// this.avatarUrl = '../../static/images/headerimg.png';
			}
		}
	}
</script>

<style>
	page{
		background-color: #fff !important;
	}
</style>

<style scoped>
	@import "../../colorui/main.css";
	@import "../../colorui/icon.css";

	.userinfo {
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.userinfo-avatar {
		width: 128rpx;
		height: 128rpx;
		margin: 20rpx;
		border-radius: 50%;
	}

	.userinfo-nickname {
		color: #aaa;
	}

	.chat {
		font-size: 35rpx;
		margin: 40rpx 0;
	}

	.contents {
		padding: 20rpx 100rpx;
		text-align: center;
	}

	.authorize {
		text-align: center;
	}

	.top image {
		width: 100%;
		height: 360rpx;
	}

	.loginTitle {
		margin: 10rpx;
		color: #fff;
		background-color: #142372;
		width: 180rpx;
		position: absolute;
		left: 50%;
		transform: translateX(-50%);
	}

	.loginTitle1 {
		margin-top: 60rpx;
		margin-bottom: 20rpx;
	}

	.loginTitle1,
	.loginTitle2 {
		color: #192576;
	}

	.info-wrap {
		margin-top: 20rpx;
		border: 4rpx solid #142372;
		border-radius: 8rpx;
		padding: 40rpx;
		display: flex;
		justify-content: space-between;
		flex-wrap: wrap;
	}

	.info-item {
		display: table;
		color: #142372;
	}

	.info image {
		width: 40rpx;
		height: 40rpx;
		vertical-align: middle;
		display: table-cell;
	}

	.info text {
		display: inline-block;
		font-size: 30rpx;
	}

	.bottom {
		position: absolute;
		bottom: 0;
		left: 50%;
		transform: translateX(-50%);
	}

	.bottom button,
	.bottom2 button {
		width: 300rpx;
		height: 80rpx;
		line-height: 80rpx;
		/* background-color: #FFDD00; */
		background-color: #142372;
		color: #fff;
		border-radius: 25rpx;
		border: 0;
		margin-bottom: 40rpx;
	}
	
	.margin-right-sm{
		margin-right: 10rpx;
	}
</style>
